import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from "axios";
//#ifdef APP-PLUS
import axiosAdapterUniApp from "axios-adapter-uniapp";
//#endif

import { ResultData } from "@/api/interface";
import { ResultEnum } from "@/enums/httpEnum";
import { checkStatus } from "./helper/checkStatus";
import { useUserStore } from "@/stores/modules/user";
const config: any = {
  // 默认地址请求地址，可在 .env.** 文件中修改
  baseURL: basicUrl(),
  // 设置超时时间
  timeout: ResultEnum.TIMEOUT as number,
  // 跨域时候允许携带凭证
  withCredentials: true,
  adapter: isAPP() ? axiosAdapterUniApp : ""
};

class RequestHttp {
  service: AxiosInstance;
  public constructor(config: AxiosRequestConfig) {
    // instantiation
    this.service = axios.create(config);

    /**
     * @description 请求拦截器
     * 客户端发送请求 -> [请求拦截器] -> 服务器
     * token校验(JWT) : 接受服务器返回的 token,存储到 vuex/pinia/本地储存当中
     */
    this.service.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        const globalStore = useGlobalStore();
        const userStore = useUserStore();
        globalStore.loading = true;
        console.log(config, "config");
        if (!isDev()) {
          if (config.url.includes("/task/")) {
            config.baseURL = "http://106.54.55.38:8080";
          } else {
            console.log("=============");

            config.baseURL = "http://106.54.55.38:8889";
          }
        }

        if (config.headers && typeof config.headers.set === "function") {
          config.headers.set("TOKEN", userStore.token);
          config.headers.set("userName", userStore.username);
        }

        // this.setBasicParams(config);
        return config;
      },
      (error: AxiosError) => {
        return Promise.reject(error);
      }
    );

    /**
     * @description 响应拦截器
     *  服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
     */
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const globalStore = useGlobalStore();

        const { code, data, message } = response.data || {};
        if (response?.request?.responseType && response?.request?.responseType === "blob") {
          return response.data;
        }

        const userStore = useUserStore();

        // 登陆失效
        if (code == ResultEnum.OVERDUE) {
          globalStore.setMessage("登录过期即将返回登录页面", "error");
          userStore.setToken("");
          uni.redirectTo({ url: "/pages/login/index" });
          return Promise.reject(data);
        }

        // 全局错误信息拦截（防止下载文件的时候返回数据流，没有 code 直接报错）
        if (code && code !== ResultEnum.SUCCESS) {
          globalStore.setMessage(message, "error");

          return Promise.reject(data);
        }
        closeLoading();

        // 成功请求（在页面上除非特殊情况，否则不用处理失败逻辑）
        return data;
      },
      async (error: AxiosError) => {
        const globalStore = useGlobalStore();
        const { response } = error;
        closeLoading();
        // 请求超时 && 网络错误单独判断，没有 response
        if (error.message.indexOf("timeout") !== -1) {
          globalStore.setMessage("请求超时！请您稍后重试！", "error");
        }
        if (error.message.indexOf("Network Error") !== -1) {
          globalStore.setMessage("网络错误！请您稍后重试！", "error");
        }
        // 根据服务器响应的错误状态码，做不同的处理
        if (response) checkStatus(response.status);
        // 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
        if (!window.navigator.onLine) {
          // router.replace("/500");
        }
        return Promise.reject(error);
      }
    );
  }

  setBasicParams(config: AxiosRequestConfig) {
    const { method } = config;
    const { systemCode: code } = config.data || {};
    const userStore = useUserStore();

    const systemCode = "NMES";
    const { name } = userStore.userInfo;
    if (method === "post") {
      config.data = {
        systemCode: code || systemCode,
        ...config.data,
        douser: name
      };
    } else if (method === "get") {
      config.params = {
        systemCode: code || systemCode,
        ...config.params,
        douser: name
      };
    }
  }

  /**
   * @description 常用请求方法封装
   */
  get<T>(url: string, params?: object, _object = {}): Promise<T> {
    return this.service.get(url, { params, ..._object });
  }
  post<T>(url: string, params?: object | string, _object = {}): Promise<T> {
    return this.service.post(url, params, _object);
  }
  put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.put(url, params, _object);
  }
  delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
    return this.service.delete(url, { params, ..._object });
  }
  download(url: string, params?: object, _object = {}): Promise<BlobPart> {
    return this.service.post(url, params, { ..._object, responseType: "blob" });
  }
  getDownload(url: string, params?: object, _object = {}): Promise<BlobPart> {
    return this.service.get(url, { params, ..._object, responseType: "blob" });
  }
}

const closeLoading = () => {
  const globalStore = useGlobalStore();
  globalStore.loading = false;
  globalStore.modalLoading = false;
};

export default new RequestHttp(config);
